/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.db_vdumper.actions;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import org.opu.db_vdumper.actions.db.DbAction;
import org.opu.db_vdumper.beans.ApplicationData;
import org.opu.db_vdumper.io.FileIO;
import org.opu.db_vdumper.resources.ConfigPath;
import org.opu.db_vdumper.util.DbManager;
import org.opu.db_vdumper.util.Logger;
import org.opu.db_vdumper.ui.component.db.ConnectionDialog;
import org.opu.db_vdumper.ui.component.db.ConnectionDialogI18n;
import org.opu.db_vdumper.ui.i18n.PropertiesPanelI18N;
import org.opu.db_vdumper.util.monitors.SimpleProgresMonitorImpl;

/**
 *
 * @author yura
 */
public class OkAction extends AbstractAction {

    private ConnectionDialog dialog;
    private ApplicationData data;
    private final Map<String, DbAction> connectActions;

    public OkAction(ApplicationData data, Map<String, DbAction> connectActions) {
        this(data, null, connectActions);
    }

    public OkAction(ApplicationData data, ConnectionDialog dialog, 
            Map<String, DbAction> connectActions) {

        this.dialog = dialog;
        this.data = data;
        this.connectActions = connectActions;
    }

    public void setDialog(ConnectionDialog dialog) {
        this.dialog = dialog;
    }

    @Override
    public void action(ActionEvent e) {
        final ConnectionDialogI18n i18n = dialog.getI18n();

        try {
            data.setDbData(dialog.getDbData());
        } catch (ClassNotFoundException ex) {
            err(i18n, new String[]{i18n.getErrorMsgConnectfailed(),
                        i18n.getErrorMsgClassnotfound(), String.valueOf(ex)});
            return;
        } catch (SQLException ex) {
            err(i18n, new String[]{i18n.getErrorMsgConnectfailed(),
                        i18n.getErrorMsgSql(), String.valueOf(ex)});
            return;
        }

        Logger.getInstance().info(this, "Connected");
        close();

        new Thread() {

            @Override
            public void run() {
                final File f = ConfigPath.getInstance().getUserDbProp();
                boolean b = dialog.getDbDataPane().isSavePasswordSelected();
                try {
                    FileIO.store(f, dialog.getDbData().properties(b), "");
                    Logger.getInstance().info(OkAction.this, "Data srored to " + f);
                } catch (IOException ex) {
                    Logger.getInstance().warning(OkAction.this, ex);
                }
            }
        }.start();

        final SimpleProgresMonitorImpl monitor = new SimpleProgresMonitorImpl(
                data.getMainView().asFrame(), data.getI18N().getName());

        new Thread() {

            @Override
            public void run() {
                monitor.setProgress(3);
                Logger.getInstance().debug(this, "Data started: " + !monitor.isCanceled());
                try {
                    data.reset(monitor);
                    monitor.close();
                } catch (SQLException ex) {
                    monitor.close(); // not final beacouse first show error
                    err(i18n, new String[]{i18n.getErrorMsgConnectfailed(),
                                i18n.getErrorMsgSql(), String.valueOf(ex)});
                }
            }
        }.start();

        monitor.setVisible(true);

        DbManager db = data.getDbManager();

        for (DbAction actn : connectActions.values()) {
            actn.setDbManager(db);
        }
        
        Map<String, String> prop = new LinkedHashMap<String, String>();
        try {
            DatabaseMetaData metaData = db.getConnection().getMetaData();
            prop.put(PropertiesPanelI18N.DB_PRODUCT_NAME, metaData.getDatabaseProductName());
            prop.put(PropertiesPanelI18N.DB_PRODUCT_VERSION, metaData.getDatabaseProductVersion());
            prop.put(PropertiesPanelI18N.DB_DRIVER_NAME, metaData.getDriverName());
            prop.put(PropertiesPanelI18N.DB_DRIVER_VERSION, metaData.getDriverVersion());
            prop.put(PropertiesPanelI18N.DB_URL, db.getDbUrlString());
        } catch (SQLException ex) {
            Logger.getInstance().error(this, "Can't set database properties: ");
            Logger.getInstance().error(this, ex);
        }
        data.getMainView().setDbProp(prop);
    }

    @Override
    public String getName() {
        return "Ok";
    }

    public void close() {
        try {
            dialog.dispose();
        } catch (Exception e) {
            Logger.getInstance().warning(this, "Can't dispose dialog: ");
            Logger.getInstance().warning(this, e);
        }
        dialog.setVisible(false);
    }

    public void err(ConnectionDialogI18n i18n, String... msg) {

        StringBuilder sb = new StringBuilder();

        for (String s : msg) {
            Logger.getInstance().error(this, s);
            sb.append(s).append('\n');
        }

        try {
            JOptionPane.showMessageDialog(dialog, sb.toString(),
                    i18n.getTitle(), JOptionPane.ERROR_MESSAGE);
        } catch (HeadlessException ex) {
            Logger.getInstance().error(this, "Can't show dialog-box: ");
            Logger.getInstance().error(this, ex);
        }
    }
}
